package com.nativetalk.service.teacher.update;

import com.aliyun.openservices.oss.model.ObjectMetadata;
import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.TdNtTeacher;
import com.nativetalk.bean.TsNtCourseInfo;
import com.nativetalk.bean.member.TdNtMemberGetui;
import com.nativetalk.bean.teacher.*;
import com.nativetalk.common.Constants;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.getui.AndroidStudentGetui;
import com.nativetalk.common.getui.IosStudentGetui;
import com.nativetalk.common.oss.OssUtil;
import com.nativetalk.common.util.MD5;
import com.nativetalk.common.util.MemcachedUtils;
import com.nativetalk.dao.TdNtTeacherDao;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lizhun on 16/1/8.
 */
@Service
public class TeacherUpdateServiceImpl implements TeacherUpdateService {
    @Resource
    private TdNtTeacherDao tdNtTeacherDao;
    private static Logger logger = Logger.getLogger(TeacherUpdateServiceImpl.class);

    @Override
    public RetInfo updateTeacher(TdNtTeacherResult tdNtTeacherResult) {
        String logInfo = this.getClass().getName() + ":updateTeacher:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            tdNtTeacherDao.updateTdNtTeacher(tdNtTeacherResult);
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip(ValidationMessages.getValue("TEACHER.UPDATE.SUCCESS"));
            MemcachedUtils.replace(tdNtTeacherResult.getToken(), tdNtTeacherResult, 20 * 24 * 60 * 60);
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(),e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo updateTeacherPsd(TdNtTeacherPsd tdNtTeacherPsd, TdNtTeacherResult tdNtTeacherResult) {
        String logInfo = this.getClass().getName() + ":updateTeacherPsd:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            if (tdNtTeacherResult.getTea_password().equals(MD5.code(tdNtTeacherPsd.getOld_tea_password()))) {
                tdNtTeacherResult.setTea_password(MD5.code(tdNtTeacherPsd.getTea_password()));
                tdNtTeacherDao.updateTdNtTeacher(tdNtTeacherResult);
                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setTip(ValidationMessages.getValue("TEACHER.UPDATE.PSD.SUCCESS"));
                MemcachedUtils.replace(tdNtTeacherResult.getToken(), tdNtTeacherResult, 20 * 24 * 60 * 60);

            } else {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip(ValidationMessages.getValue("TEACHER.UPDATE.PSD.ERROR"));
            }

        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(),e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo updateTeacherState(TdNtTeacherState tdNtTeacherState) {
        String logInfo = this.getClass().getName() + ":updateTeacherState:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            tdNtTeacherDao.updateTdNtTeacherState(tdNtTeacherState);
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("操作成功");
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(),e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo updateTeacherStateTwo(TdNtTeacherState tdNtTeacherState) {
        String logInfo = this.getClass().getName() + ":updateTeacherState:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            TdNtTeacher tdNtTeacher = tdNtTeacherDao.findTdNtTeacherOn(tdNtTeacherState.getTea_id());
            if (tdNtTeacher.getTea_name().equals("NativeTalk")) {
                retInfo.setMark("2");
                retInfo.setTip("Please change username");
            } else if (tdNtTeacher.getTea_sex() == null) {
                retInfo.setMark("3");
                retInfo.setTip("Please select your gender");
            } else if (tdNtTeacher.getTea_synopsis() == null) {
                retInfo.setMark("4");
                retInfo.setTip("Tell us more about yourself");
            } else if (tdNtTeacher.getDict_id() == null) {
                retInfo.setMark("5");
                retInfo.setTip("Please find your university");
            } else {
                tdNtTeacherDao.updateTdNtTeacherState(tdNtTeacherState);
                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setTip("操作成功");
            }

        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(),e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }
    @Override
    public RetInfo updateTeacherStateThree(TdNtTeacherState tdNtTeacherState) {
        String logInfo = this.getClass().getName() + ":updateTeacherState:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            List<TsNtCourseInfo> courseList = tdNtTeacherDao.findTeacherOpenCourseInfo(tdNtTeacherState.getTea_id());
            if (courseList != null && courseList.size() > 0) {
                TdNtTeacher tdNtTeacher = tdNtTeacherDao.findTdNtTeacherOn(tdNtTeacherState.getTea_id());
                if (tdNtTeacher.getTea_name().equals("NativeTalk")) {
                    retInfo.setMark("2");
                    retInfo.setTip("Please change username");
                } else if (tdNtTeacher.getTea_sex() == null) {
                    retInfo.setMark("3");
                    retInfo.setTip("Please select your gender");
                } else if (tdNtTeacher.getTea_synopsis() == null) {
                    retInfo.setMark("4");
                    retInfo.setTip("Tell us more about yourself");
                } else if (tdNtTeacher.getDict_id() == null) {
                    retInfo.setMark("5");
                    retInfo.setTip("Please find your university");
                } else {
                    tdNtTeacherDao.updateTdNtTeacherState(tdNtTeacherState);
                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                    retInfo.setTip("操作成功");
                    if ("0".equals(tdNtTeacherState.getState())){
                        //对收藏该老师的学生发送推送
                        List<TdNtMemberGetui> tdNtMemberGetuiList = tdNtTeacherDao.findTdNtMemberByTeaID(tdNtTeacherState.getTea_id());
                        for (int j = 0; j < tdNtMemberGetuiList.size(); j++) {
                            //判断该用户对该老师是否开启上线提醒
                            Map<String, Object> obj = new HashMap<String, Object>();
                            obj.put("tea_id",tdNtTeacherState.getTea_id());
                            obj.put("memb_id",tdNtMemberGetuiList.get(j).getMemb_id());
                            //给查询到的老师教师信息添加是否上线字段
                            String flag = tdNtTeacherDao.foundTdNtTeacherOnline(obj);
                            if ("0".equals(flag)){
                                if (MemcachedUtils.get(tdNtMemberGetuiList.get(j).getToken()) != null) {
                                    if (tdNtMemberGetuiList.get(j).getEqu_client_id() != null) {
                                        if (tdNtMemberGetuiList.get(j).getEqu_type().equals("1")) {
                                            AndroidStudentGetui.funspush("NativeTalk", "你关注的老师已上线! ",
                                                    tdNtMemberGetuiList.get(j).getEqu_client_id(), tdNtTeacherState.getTea_id());
                                        } else {
                                            IosStudentGetui.funspush("NativeTalk", "你关注的老师已上线! ",
                                                    tdNtMemberGetuiList.get(j).getEqu_client_id(), tdNtTeacherState.getTea_id());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

            } else {
                retInfo.setMark("1");
                retInfo.setTip("Please open subjects");
            }


        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(),e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo updateTeacherPortrait(TdNtTeacherPortrait tdNtTeacherPortrait, TdNtTeacherResult tdNtTeacherResult) throws IOException {
        String logInfo = this.getClass().getName() + ":updateTeacherPortrait:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        //上传头像
        CommonsMultipartFile commonsMultipartFile = tdNtTeacherPortrait.getHead_portrait();
        if (commonsMultipartFile != null && commonsMultipartFile.getSize() > 31457280) {
            retInfo.setMark(ValidationMessages.getValue("MARKNO"));
            retInfo.setTip(ValidationMessages.getValue("HEAD.SIZE.LARGE"));
            return retInfo;
        } else {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(commonsMultipartFile.getSize());
            String headPortrait = Constants.FILE + "/" + Constants.FILEIMG + "/image/teacher/" + tdNtTeacherPortrait.getTea_id() + "/head/"
                    + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date(System.currentTimeMillis())) + "1" + commonsMultipartFile.getOriginalFilename().substring(commonsMultipartFile.getOriginalFilename().lastIndexOf("."));
            OssUtil.uploadInputStream(commonsMultipartFile.getInputStream(), objectMetadata, headPortrait);
            tdNtTeacherPortrait.setTea_head_portrait(headPortrait);
        }
        tdNtTeacherDao.updateTdNtTeacherProtrait(tdNtTeacherPortrait);
        tdNtTeacherResult.setTea_head_portrait(tdNtTeacherPortrait.getTea_head_portrait());
        MemcachedUtils.replace(tdNtTeacherResult.getToken(), tdNtTeacherResult, 20 * 24 * 60 * 60);
        retInfo.setMark(ValidationMessages.getValue("MARKYES"));
        retInfo.setTip("认证头像修改成功");
        tdNtTeacherDao.updateTdNtTeacher(tdNtTeacherResult);

        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo updateTeacherSound(TdNtTeacherSound tdNtTeacherSound, TdNtTeacherResult tdNtTeacherResult) throws IOException {
        String logInfo = this.getClass().getName() + ":updateTeacherPortrait:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        CommonsMultipartFile synopsis = tdNtTeacherSound.getSound_synopsis();
        if (synopsis != null && synopsis.getSize() > 31457280) {
            retInfo.setMark(ValidationMessages.getValue("MARKNO"));
            retInfo.setTip(ValidationMessages.getValue("SYNOPSIS.SIZE.LARGE"));
            return retInfo;
        } else {

            ObjectMetadata objectMetadataSynopsis = new ObjectMetadata();
            objectMetadataSynopsis.setContentLength(synopsis.getSize());
            String synopsisUrl = Constants.FILE + "/" + Constants.FILEIMG + "/image/teacher/" + tdNtTeacherSound.getTea_id() + "/synopsis/"
                    + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date(System.currentTimeMillis())) + "3" + synopsis.getOriginalFilename().substring(synopsis.getOriginalFilename().lastIndexOf("."));
            OssUtil.uploadInputStream(synopsis.getInputStream(), objectMetadataSynopsis, synopsisUrl);
            tdNtTeacherSound.setTea_sound_synopsis(synopsisUrl);
        }
        tdNtTeacherDao.updateTdNtTeacherSound(tdNtTeacherSound);
        tdNtTeacherResult.setTea_sound_synopsis(tdNtTeacherSound.getTea_sound_synopsis());
        MemcachedUtils.replace(tdNtTeacherResult.getToken(), tdNtTeacherResult, 20 * 24 * 60 * 60);
        retInfo.setMark(ValidationMessages.getValue("MARKYES"));
        retInfo.setTip("认证语音简介修改成功");

        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo updateTeacherCollect(Map<String, Object> obj) {
        String logInfo = this.getClass().getName() + ":updateTeacherCollect:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            int i = tdNtTeacherDao.findCollection(obj);
            if(i != 0){
                //更新
                tdNtTeacherDao.updateTeacherCollect(obj);
            }else{
                //插入
                tdNtTeacherDao.insertTeacherCollect(obj);
            }

            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("操作成功");
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(),e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }
    @Override
    public RetInfo updateTeacherOnline(Map<String, Object> obj) {
        String logInfo = this.getClass().getName() + ":updateTeacherOnline:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            int i = tdNtTeacherDao.findCollection(obj);
            if(i != 0){
                //更新
                tdNtTeacherDao.updateTeacherOnline(obj);
            }else{
                //插入
                tdNtTeacherDao.insertTeacherOnline(obj);
            }

            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("操作成功");
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(),e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    public void updateTeacherJustTalkUserUri(Integer tea_id, String justTalkUserUri) {
        tdNtTeacherDao.updateTeacherJustTalkUserUri(tea_id, justTalkUserUri);
    }
}
